package history;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GetPublicHistory {
	private PreparedStatement stmt;
	static Connection conn = null;
	private List<String> public_history = new ArrayList<String>();
	private List<String> private_history = new ArrayList<String>();
	static{
		try
	    {             
            String dbName = "MultiChat";
            String url = "jdbc:derby:" + dbName + ";create=true";
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance ();
	        conn = DriverManager.getConnection(url);
	   
	    }catch (Exception e){
	       	System.err.println ("Cannot connect to database server");
	        e.printStackTrace();
	    }  
	}
	
	public List<String> getPubHistory(String channel){
		
		try {
			String insert = "SELECT date,message FROM History WHERE room=? AND receiver = 'null'";

			stmt = conn.prepareStatement(insert);
			stmt.setString(1, channel);
			ResultSet rs = stmt.executeQuery();

	         while (rs.next())
	         {
	        	 String data = rs.getString("date");
	        	 String message = rs.getString("message");
	        	 message = data + " "+ message;
	        	 public_history.add(message);
	         }


		} catch (SQLException e) {
			e.printStackTrace();
		}

		return public_history;
		
	}
	
        	public List<String> getPrivateHistory(String channel, String receiver, String sender){
		private_history.removeAll(private_history);
		try {
                    String insert = "SELECT date,message FROM History WHERE ((room=?) AND (((receiver = ?) AND (sender = ?)) OR ((receiver = ?) AND (sender = ?))) )";
                    stmt = conn.prepareStatement(insert);
                    stmt.setString(1, channel);
                    stmt.setString(2, receiver);
                    stmt.setString(3, sender);
                    stmt.setString(4, sender);
                    stmt.setString(5, receiver);
                    ResultSet rs = stmt.executeQuery();

	         while (rs.next())
	         {
	        	 String data = rs.getString("date");
	        	 String message = rs.getString("message");
	        	 message = data + " "+ message;
	        	 private_history.add(message);
	         }


		} catch (SQLException e) {
			e.printStackTrace();
		}

		return private_history;
		
	}

}	
